﻿#region File Header
//-----------------------------------------------------------------------------
// SibLib
//
// Copyright (C) 2010 Julien Villers
// This program is distributed under the terms of the 
// GNU Lesser General Public License (LGPL).
// See Docs/lgpl.txt and Docs/gpl.txt
//
// This file is based on a sample by Nick Gravelyn:
//  http://blog.nickgravelyn.com/2009/07/a-more-robust-exception-system/
//-----------------------------------------------------------------------------
#endregion

using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using SibLib.GameComponents;

namespace SibLib
{
    /// <summary>
    /// Helper static class for program tools.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// Launch a game, includes error handling.
        /// First start by checking for debugger, if present, do nothing special.
        /// Else wrap everything in a global try/catch, and use ExceptionGame to display errors.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static void Run<T>() where T : Game, new()
        {
            if (Debugger.IsAttached)
            {
                using (var g = new T())
                    g.Run();
            }
            else
            {
                T game = null;
                try
                {
                    using (game = new T())
                        game.Run();
                }
                catch (Exception e)
                {
                    using (var g = new ExceptionGame(e, game))
                        g.Run();
                }
            }
        }
    }

    /// <summary>
    /// Make your game inherit from this if it uses GamerServices.
    /// Creation of the GSC will occur in the Initialize method.
    /// </summary>
    public class GameWithGSC : Game
    {
        public GamerServicesComponent GSC
        {
            get;
            private set;
        }

        protected override void Initialize()
        {
            base.Initialize();

#if XBOX360         // Cannot create GamerServiceComponent on Windows PC without XNA Game Studio installed.
            // Create the gamerservice component.
            // Note: must be done after base.Initialize() so only initialized component is added to Components (cf ExceptionGame).
            GSC = new GamerServicesComponent(this);
            GSC.Initialize();
            Components.Add(GSC);
#endif
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            GSC = null;
        }
    }
}
